package com.ransj.iphone.utils;


import android.app.Instrumentation;
import android.os.SystemClock;
import android.view.MotionEvent;

public class Input {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Instrumentation instruct = new Instrumentation();
		if (args != null) {
			int len = args.length;
			for (int i = 0; i < len; i++) {
				ILog.getInstance().w("TAG", "args [" + i + "] : " + args[i]);
			}
		}
		if (args.length < 1) {
			return;
		}

		String command = args[0];

		try {
			if (command.equals("text")) {
				if (args.length == 2) {
					instruct.sendStringSync(args[1]);
					return;
				}
			} else if (command.equals("keyevent")) {
				if (args.length == 2) {
					int keyCode = Integer.valueOf(args[1]);
					instruct.sendKeyDownUpSync(keyCode);
					return;
				}
			} else if (command.equals("tap")) {
				if (args.length == 3) {
					float x = Float.parseFloat(args[1]);
					float y = Float.parseFloat(args[2]);
					long now = SystemClock.uptimeMillis();
					instruct.sendPointerSync(MotionEvent.obtain(now, now,
							MotionEvent.ACTION_DOWN, x, y, 0));
					instruct.sendPointerSync(MotionEvent.obtain(now, now,
							MotionEvent.ACTION_UP, x, y, 0));
					return;
				}
			} else if (command.equals("swipe")) {
				if (args.length == 5) {
					sendSwipe(instruct, Float.parseFloat(args[1]),
							Float.parseFloat(args[2]),
							Float.parseFloat(args[3]),
							Float.parseFloat(args[4]));
					return;
				}
			} else {
				System.err.println("Error: Unknown command: " + command);
				return;
			}
		} catch (NumberFormatException ex) {
		}
	}

	private static void sendSwipe(Instrumentation instruct, float x1, float y1,
			float x2, float y2) {
		final int NUM_STEPS = 11;
		long now = SystemClock.uptimeMillis();
		instruct.sendPointerSync(MotionEvent.obtain(now, now,
				MotionEvent.ACTION_DOWN, x1, y1, 0));
		for (int i = 1; i < NUM_STEPS; i++) {
			float alpha = (float) i / NUM_STEPS;
			instruct.sendPointerSync(MotionEvent.obtain(now, now,
					MotionEvent.ACTION_MOVE, lerp(x1, x2, alpha),
					lerp(y1, y2, alpha), 0));
		}
		instruct.sendPointerSync(MotionEvent.obtain(now, now,
				MotionEvent.ACTION_UP, x2, y2, 0));
	}

	private static final float lerp(float a, float b, float alpha) {
		return (b - a) * alpha + a;
	}

}
